package com.egg.basic.service.secure;

import cn.hutool.core.util.ObjectUtil;
import com.egg.common.redis.util.RedisUtil;
import com.egg.common.swagger.param.child.SwaggerSecure;
import com.egg.common.util.HttpServletUtil;
import com.egg.common.util.OptionalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;


@Slf4j
@Service
public class SecureService {


    @Autowired
    private SwaggerSecure swaggerSecure;

    /**
     * 需要使用加密数据体的请求头的REDIS-KEY
     *
     * @param publicKey
     * @return
     */
    public String buildSecureHeaderRedisKey(String publicKey) {
        return swaggerSecure.getName() + ":" + publicKey;
    }

    /**
     * 查询对称秘钥
     *
     * @return
     */
    public Optional<String> findAesSecure() {
        HttpServletRequest request = HttpServletUtil.getHttpServletRequest();
        if (null == request) {
            return Optional.empty();
        }
        //请求头信息, 放入本地线程中
        String publicKey = request.getHeader(swaggerSecure.getName());
        return findAesSecure(publicKey);
    }

    /**
     * 查询对称秘钥
     *
     * @return
     */
    public Optional<String> findAesSecure(String publicKey) {
        if (ObjectUtil.isEmpty(publicKey)) {
            return Optional.empty();
        }
        String aesSecureKey = RedisUtil.get(buildSecureHeaderRedisKey(publicKey));
        return OptionalUtil.build(aesSecureKey);
    }

}